package com.ztgf.search.server.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ztgf.commodity.models.dto.CommodityInfoDTO;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.commodity.models.vo.CommodityEsVO;
import com.ztgf.search.models.dto.EsGoodsDTO;
import com.ztgf.search.models.dto.EsShopDTO;
import com.ztgf.search.models.service.IShopSearchService;
import com.ztgf.search.models.service.SearchService;
import com.ztgf.search.models.service.SynchronizationService;
import com.ztgf.search.models.vo.SynchronizationVo;
import com.ztgf.search.server.utils.CollectionHelp;
import com.ztgf.search.server.utils.StringHelper;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.ztgf.common.utils.UtilConstants.isNull;

/**
 * @author ：Eric
 * @description：TODO
 * @date ：2021/8/16 11:13
 */
@Slf4j
@DubboService
public class SynchronizationServiceImpl implements SynchronizationService {
    @DubboReference
    private ICommodityInfoService commodityInfoService;
    @Resource
    private ElasticsearchServiceImpl elasticsearchService;
    @DubboReference
    private IShopInfoService shopInfoService;
    @DubboReference
    private IShopSearchService shopSearchService;
    @DubboReference
    private SearchService searchService;
    @Qualifier("restHighLevelClient")
    @Autowired
    public RestHighLevelClient client;


    @Override
    public SynchronizationVo selectESAndShop() {
        SynchronizationVo synchronizationVo = new SynchronizationVo();
        //获取数据库中店铺数量
        Wrapper<ShopInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("merchant_type", 1)
                .eq("frozen_status", 0)
                .eq("admin_frozen_status", 0)
                .eq("check_agreement_status",1);
        int shopSize = shopInfoService.selectCount(wrapper);
        synchronizationVo.setShopNum(shopSize);

        int goodsSize = commodityInfoService.queryAllESGoodsCount();
        synchronizationVo.setGoodsNum(goodsSize);


        //Es中商品和店铺数量
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(1);

        //检查店铺是否存在
        boolean b = shopSearchService.checkIndex("index_shop_2020");
        if(b){
            List<String> esShopIdDTOList = new ArrayList<>();
            SearchRequest searchRequestShop = new SearchRequest("index_shop_2020");
            searchRequestShop.source(searchSourceBuilder);
            searchRequestShop.types("shop");
            SearchResponse searchShop = null;
            try {
                searchShop = client.search(searchRequestShop, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            SearchHit[] hits1 = searchShop.getHits().getHits();
            if (CollectionHelp.isArrayNotEmpty(hits1)) {
                synchronizationVo.setShopEsNum(searchShop.getHits().getTotalHits());
            }
        }


        //检查商品索引是否存在
        boolean b2 = searchService.checkIndex("index_goods_2020");
        if(b2){
            List<String> EsGoodsIdDTOList = new ArrayList<>();
            SearchRequest searchRequest = new SearchRequest("index_goods_2020");
            searchRequest.types("goods");
            searchRequest.source(searchSourceBuilder);
            SearchResponse search = null;
            try {
                search = client.search(searchRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            SearchHit[] hits = search.getHits().getHits();
            if (CollectionHelp.isArrayNotEmpty(hits)) {
                synchronizationVo.setGoodsEsNum(search.getHits().getTotalHits());
            }
        }
        return synchronizationVo;
    }

    @Override
    public boolean updateEsShopAndGoods() {
        try {
            //检查店铺是否存在
            boolean b = shopSearchService.checkIndex("index_shop_2020");
            if(b){
                shopSearchService.add();
            }

            //检查商品索引是否存在
            boolean b2 = searchService.checkIndex("index_goods_2020");
            if(b2){
                synAllGoods(0);
            }
        }catch (Exception e){
            log.error("同步es数据", e);
            return false;
        }
        return true;
    }


    private void synAllGoods(long offset){
        //查询出数据库中的商品进行封装
        List<CommodityEsVO> list = commodityInfoService.queryAllESGoods(offset);
        log.info("ESlist----------------------"+list.size());
        if (isNull(list)) {
            log.error("定时任务：凌晨同步es数据：查询商品为空");
        }else{
            List<EsGoodsDTO> goodsList = new ArrayList<>();
            for (CommodityEsVO vo : list) {
                EsGoodsDTO goodsDTO = new EsGoodsDTO();
                goodsDTO.setId(vo.getId());
                goodsDTO.setLogUrl(vo.getLogUrl());
                goodsDTO.setGoodsName(vo.getGoodsName());
                goodsDTO.setGoodsNameIkSmart(vo.getGoodsName());
                goodsDTO.setGoodsNameIkMaxWord(vo.getGoodsName());
                goodsDTO.setDescription(vo.getDescription());
                goodsDTO.setPrice(vo.getPrice().doubleValue());
                goodsDTO.setOriginalPrice(vo.getOriginalPrice().doubleValue());
                goodsDTO.setPayUserNum(vo.getPayUserNum());
                goodsDTO.setSellerShopId(vo.getSellerShopId());
                goodsDTO.setSellerShopName(vo.getSellerShopName());
                goodsDTO.setSellerShopAddress(vo.getSellerShopAddress());
                goodsDTO.setBrandId(vo.getBrandId().toString());
                goodsDTO.setBrandName(vo.getBrandName());
                goodsDTO.setBrandNameIkSmart(vo.getBrandName());
                goodsDTO.setBrandNameIkMaxWord(vo.getBrandName());
                goodsDTO.setCategoryId(vo.getCategoryId());
                goodsDTO.setCategoryName(vo.getCategoryName());
                goodsDTO.setIsNew(vo.getIsNew());
                goodsDTO.setPopularity(vo.getPopularity());
                goodsDTO.setEvaluationNum(vo.getEvaluationNum());
                goodsDTO.setCreateTime(vo.getCreateTime());
                goodsDTO.setParentCategoryId(vo.getParentCategoryId());
                goodsDTO.setFirstCategoryId(vo.getFirstCategoryId());
                goodsDTO.setFilterIds(vo.getFilterIds());
                goodsDTO.setFilterNames(vo.getFilterNames());
                if (StringHelper.isNotEmpty(vo.getFilterNames())) {
                    String[] split = vo.getFilterNames().split(",");
                    goodsDTO.setFilterName(split);
                }
                if (StringHelper.isNotEmpty(vo.getLabelIds())) {
                    String[] split = vo.getLabelIds().split(",");
                    goodsDTO.setLabelIds(split);
                }
                goodsDTO.setIsXun(vo.getIsXun());
                goodsDTO.setBrowseAmount(vo.getBrowseAmount());
                goodsList.add(goodsDTO);
            }
            log.info("-------------goodsList=="+goodsList.size());
            searchService.addGoods("index_goods_2020", "goods", 0, goodsList.size(), goodsList);
            synAllGoods(offset + goodsList.size());
        }
    }

    @Override
    public boolean deleteEsIndex(String index) {
        try {
            //检查店铺是否存在
            boolean b = shopSearchService.checkIndex(index);
            if(b){
                elasticsearchService.deleteIndex(index);
                CommodityInfoDTO dto = new CommodityInfoDTO();
                dto.setIsSynEs(0);
                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("is_syn_es",1);
                commodityInfoService.update(dto,wrapper);
                return true;
            }
        }catch (Exception e){
            log.error("删除索引失败", e);
            return false;
        }
        return true;
    }
}
